<template>
  <view>
    <s-layout :onShareAppMessage="shareInfo" navbar="none">
      <!-- 标题栏 -->
      <detailNavbar />

      <!-- 骨架屏 -->
      <detailSkeleton v-if="state.skeletonLoading" />
      <!-- 下架/售罄提醒 -->
      <s-empty
        v-else-if="state.goodsInfo === null"
        text="商品不存在或已下架"
        icon="/static/soldout-empty.png"
        showAction
        actionText="再逛逛"
        actionUrl="/pages/goods/list"
      />
      <block v-else>
        <view class="detail-swiper-selector">
          <!-- 商品轮播图  -->
          <su-swiper
            class="ss-m-b-14"
            isPreview
            :list="formatGoodsSwiper(state.goodsInfo.sliderPicUrls)"
            otStyle="tag"
            imageMode="fill"
            dotCur="bg-mask-40"
            :seizeHeight="750"
          />
          <view
            class="uno-flex uno-flex-justify-between uno-bg-red uno-p-2 uno-color-white uno-h-120"
          >
            <view class="uno-flex uno-justify-between uno-flex-col">
              <view>
                <text>{{ state.goodsInfo.price }}元+</text>
                <text style="font-size: 40rpx">{{ state.goodsInfo.points }}积分</text>
                <text class="uno-decoration-through" style="text-decoration: line-through"
                  >￥{{ state.goodsInfo.marketPrice }}
                </text>
              </view>

              <view
                >兑换热度{{
                  state.goodsInfo.heat ? (state.goodsInfo.heat / 10000).toFixed(1) : '10'
                }}万+</view
              >
            </view>

            <view class="uno-flex uno-justify-between uno-flex-col">
              <view class="uno-flex uno-items-center uno-justify-end">
                <up-avatar
                  text="兑"
                  fontSize="15"
                  size="20"
                  color="#fff"
                  bg-color="transparent"
                  class="uno-border-color-white uno-border-style-solid uno-mr2"
                />
                <text>限时兑换</text>
              </view>
              <view>积分已省￥{{ state.goodsInfo.marketPrice - state.goodsInfo.price }}</view>
            </view>
          </view>

          <view class="uno-bg-white uno-p2">
            <view
              class="uno-inline-block uno-bg-red uno-mr-5"
              style="background-image: url('/static/images/DetailsPagePointDeduction.png')"
            >
              <!--              <img src="/static/images/DetailsPagePointDeduction.png" alt=""/>-->
              <text class="uno-color-white">可积分抵扣</text>
            </view>
            <text class="uno-font-bold uno-color-black" style="font-size: 40rpx">
              {{ state.goodsInfo.introduction }}
            </text>

            <view
              @tap="state.showSelectSku = true"
              class="uno-border-rd uno-flex uno-items-center uno-justify-center uno-h80 uno-color-white uno-mt5 uno-mb5"
              style="background: linear-gradient(to right, rgb(255, 36, 0), rgb(254, 160, 5))"
            >
              立即兑换
            </view>

            <view
              class="uno-bg-#f2f2f2 uno-border-rd uno-flex-col uno-items-center uno-justify-center uno-p2"
              v-if="recommendReason && recommendReason.length > 0"
            >
              <view class="uno-color-red uno-w[100%]"> 推荐理由 </view>
              <view class="uno-w[100%]" v-for="(item, index) in recommendReason">
                {{ item }}
              </view>
            </view>
          </view>
          <view
            style="display: flex; justify-content: space-between; color: #a37f6c"
            class="uno-h50 uno-bg-white uno-p2 uno-mt2"
          >
            <text class="uno-font-bold">放心购</text>
            <view class="flex">
              <fontIcon modelValue="赔" :styles="{ marginRight: '10rpx' }" />
              差必赔
            </view>
            <view class="flex">
              <fontIcon modelValue="退" :styles="{ marginRight: '10rpx' }" />
              七天退换
            </view>
            <view class="flex">
              <fontIcon modelValue="邮" :styles="{ marginRight: '10rpx' }" />
              全场包邮
            </view>
            <view class="flex">
              <fontIcon modelValue="24" :styles="{ marginRight: '10rpx' }" />
              48小时发货
            </view>
          </view>

          <view class="uno-bg-white uno-mt2 uno-mb2">
            <view
              class="uno-flex uno-justify-between uno-bg-white uno-p2 uno-mt2 uno-mb5 uno-font-bold uno-items-center"
            >
              <view class="">
                <text>{{ 229 }}人在兑换,仅剩{{ item.stock }}件</text>
              </view>
              <view class="uno-color-red uno-text-center">
                <view>限时抢购</view>
                <view>
                  <up-count-down
                    :time="30 * 60 * 60 * 1000"
                    format="DD:HH:mm:ss"
                    autoStart
                    millisecond
                    @change="onChange"
                  >
                    <view class="time">
                      <text class="time__item">{{ timeData.days }}&nbsp;天</text>
                      <text class="time__item">
                        {{ timeData.hours > 10 ? timeData.hours : '0' + timeData.hours }}&nbsp;时
                      </text>
                      <text class="time__item">{{ timeData.minutes }}&nbsp;分</text>
                      <text class="time__item">{{ timeData.seconds }}&nbsp;秒</text>
                    </view>
                  </up-count-down>
                </view>
              </view>
            </view>
            <up-notice-bar
              :text="noticeList"
              icon=""
              bgColor="transparent"
              color="#000"
              direction="column"
              speed="250"
              class="custom-notice-bar"
            />
          </view>


          <!-- 功能卡片 -->
          <view class="detail-cell-card ss-flex-col uno-mb2" style="background-color: #fff">
            <detail-cell-sku
              v-model="state.selectedSku.goods_sku_text"
              :sku="state.selectedSku"
              @tap="state.showSelectSku = true"
            />
          </view>

          <!-- 规格与数量弹框 -->
          <s-select-sku
            :goodsInfo="state.goodsInfo"
            :show="state.showSelectSku"
            @add-cart="onAddCart"
            @buy="onBuy"
            @change="onSkuChange"
            @close="state.showSelectSku = false"
          />

          <view class="uno-p2 uno-mb2" style="background-color: #fff">
            <view class="uno-pb5">积分精品推荐</view>

            <up-grid :border="false" col="3" gap="20rpx">
              <up-grid-item
                v-for="(listItem, listIndex) in state.goodsInfo.relatedProductList"
                :key="listIndex"
                @click="sheep.$router.go('/pages/goods/index', { id: listItem.id })"
              >
                <jifenJp :model-value="listItem" />
              </up-grid-item>
            </up-grid>
          </view>
          <!-- 价格+标题 -->
          <!--          <view class="title-card detail-card ss-p-y-40 ss-p-x-20" v-if="false">-->
          <!--            <view class="ss-flex ss-row-between ss-col-center ss-m-b-26">-->
          <!--              <view class="price-box ss-flex ss-col-bottom">-->
          <!--                <view class="price-text ss-m-r-16">-->
          <!--                  {{ fen2yuan(state.selectedSku.price || state.goodsInfo.price) }}-->
          <!--                </view>-->
          <!--                <view class="origin-price-text" v-if="state.goodsInfo.marketPrice > 0">-->
          <!--                  {{ fen2yuan(state.selectedSku.marketPrice || state.goodsInfo.marketPrice) }}-->
          <!--                </view>-->
          <!--              </view>-->
          <!--              <view class="sales-text">-->
          <!--                {{ formatSales('exact', state.goodsInfo.salesCount) }}-->
          <!--              </view>-->
          <!--            </view>-->
          <!--            <view class="discounts-box ss-flex ss-row-between ss-m-b-28">-->
          <!--              &lt;!&ndash; 满减送/限时折扣活动的提示 &ndash;&gt;-->
          <!--              <div class="tag-content">-->
          <!--                <view class="tag-box ss-flex">-->
          <!--                  <view class="tag ss-m-r-10" v-for="promos in state.activityInfo"-->
          <!--                        :key="promos.id" @tap="onActivity">-->
          <!--                    {{ promos.name }}-->
          <!--                  </view>-->
          <!--                </view>-->
          <!--              </div>-->

          <!--              &lt;!&ndash; 优惠劵 &ndash;&gt;-->
          <!--              <view class="get-coupon-box ss-flex ss-col-center ss-m-l-20" @tap="state.showModel = true"-->
          <!--                    v-if="state.couponInfo.length">-->
          <!--                <view class="discounts-title ss-m-r-8">领券</view>-->
          <!--                <text class="cicon-forward"></text>-->
          <!--              </view>-->
          <!--            </view>-->
          <!--            <view class="title-text ss-line-2 ss-m-b-6">{{ state.goodsInfo.name }}</view>-->
          <!--            <view class="subtitle-text ss-line-1">{{ state.goodsInfo.introduction }}</view>-->
          <!--          </view>-->

        </view>

        <!-- 评价 -->
        <view class="uno-p2 uno-mb2" style="background-color: #fff">
          <detail-comment-card class="detail-comment-selector" :goodsId="state.goodsId" />
        </view>
        <!-- 详情 -->
        <view class="uno-p2 uno-mb2" style="background-color: #fff">
          <detail-content-card
            class="detail-content-selector"
            :content="state.goodsInfo.description"
        />
        </view>

        <!-- 活动跳转：拼团/秒杀/砍价活动 -->
        <!--        <detail-activity-tip v-if="state.activityList.length > 0" :activity-list="state.activityList" />-->

        <!-- 详情 tabbar -->
        <detail-tabbar v-model="state.goodsInfo">
          <view class="buy-box ss-flex ss-col-center uno-h-[100%]" v-if="state.goodsInfo.stock > 0">
            <!--            <button class="ss-reset-button add-btn ui-Shadow-Main" @tap="state.showSelectSku = true">-->
            <!--              加入购物车-->
            <!--            </button>-->
            <view
              class="uno-flex uno-flex-col uno-flex-justify-center uno-items-center uno-pr4 uno-pl4 uno-w-200"
              style="border-left: 1rpx solid #c2c7cf; box-sizing: border-box; height: 100%"
              @tap="() => {

                state.showSelectSku = true
              }"
            >
              <text class="u-line-1">{{ state.goodsInfo.marketPrice }}元</text>
              <text>直接购买</text>
            </view>
            <view
              class="forward-color uno-flex uno-justify-center uno-items-center uno-flex-col"
              @tap="() => {

                state.showSelectSku = true
              }"
            >
              立即兑换
              <text> 积分即将过期 </text>
            </view>
          </view>
          <view class="buy-box ss-flex ss-col-center ss-p-r-20" v-else>
            <button class="ss-reset-button disabled-btn" disabled> 已售罄</button>
          </view>
        </detail-tabbar>

        <!-- 优惠劵弹窗 -->
        <!--        <s-coupon-get v-model="state.couponInfo" :show="state.showModel" @close="state.showModel = false"-->
        <!--                      @get="onGet" />-->

        <!-- 满减送/限时折扣活动弹窗 -->
        <!--        <s-activity-pop v-model="state.activityInfo" :show="state.showActivityModel"-->
        <!--                        @close="state.showActivityModel = false" />-->
      </block>
    </s-layout>

    <!--    <scrollList @loadMore="loadMore" :data="scrollData">-->
    <!--      <template #default="{item}">-->
    <!--        <HotItem :model-value="item"></HotItem>-->
    <!--      </template>-->
    <!--    </scrollList>-->

    <view class="uno-p2">
      <businessScrollList tp-name="好物连连" />
    </view>
  </view>
</template>

<script setup>
  import { reactive, computed, ref, onMounted } from 'vue';
  import { onLoad, onPageScroll, onReachBottom } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import CouponApi from '@/sheep/api/promotion/coupon';
  import ActivityApi from '@/sheep/api/promotion/activity';
  import FavoriteApi from '@/sheep/api/product/favorite';
  import { formatSales, formatGoodsSwiper, fen2yuan } from '@/sheep/hooks/useGoods';
  import detailNavbar from './components/detail/detail-navbar.vue';
  import detailCellSku from './components/detail/detail-cell-sku.vue';
  import detailTabbar from './components/detail/detail-tabbar.vue';
  import detailSkeleton from './components/detail/detail-skeleton.vue';
  import detailCommentCard from './components/detail/detail-comment-card.vue';
  import detailContentCard from './components/detail/detail-content-card.vue';
  import detailActivityTip from './components/detail/detail-activity-tip.vue';
  import { isEmpty } from 'lodash-es';
  import SpuApi from '@/sheep/api/product/spu';
  import SLayout from '@/sheep/components/s-layout/s-layout.vue';
  import fontIcon from '@/sheep/businessCom/fontIcon.vue';
  import jifenJp from '@/sheep/businessCom/jifen-jp.vue';
  import businessScrollList from '@/sheep/businessCom/business-scroll-list.vue';

  onPageScroll(() => {});

  const isLogin = computed(() => sheep.$store('user').isLogin);
  const state = reactive({
    goodsId: 0,
    skeletonLoading: true, // SPU 加载中
    goodsInfo: {}, // SPU 信息
    showSelectSku: false, // 是否展示 SKU 选择弹窗
    selectedSku: {}, // 选中的 SKU
    showModel: false, // 是否展示 Coupon 优惠劵的弹窗
    couponInfo: [], // 可领取的 Coupon 优惠劵的列表
    showActivityModel: false, // 【满减送/限时折扣】是否展示 Activity 营销活动的弹窗
    activityInfo: [], // 【满减送/限时折扣】可参与的 Activity 营销活动的列表
    activityList: [], // 【秒杀/拼团/砍价】可参与的 Activity 营销活动的列表
  });

  // 规格变更
  function onSkuChange(e) {
    state.selectedSku = e;
  }

  // 添加购物车
  function onAddCart(e) {
    if (!e.id) {
      sheep.$helper.toast('请选择商品规格');
      return;
    }
    sheep.$store('cart').add(e);
  }

  // 立即购买
  function onBuy(e) {
    console.log("选中的规格", state.selectedSku);
    if (!state.selectedSku.id) {
      sheep.$helper.toast('请选择商品规格');
      return;
    }
    sheep.$router.go('/pages/order/confirm', {
      data: JSON.stringify({
        items: [
          {
            skuId: e.id,
            count: e.goods_num,
            categoryId: state.goodsInfo.categoryId,
          },
        ],
      }),
    });
  }

  // 营销活动
  function onActivity() {
    state.showActivityModel = true;
  }

  // 立即领取
  async function onGet(id) {
    const { code } = await CouponApi.takeCoupon(id);
    if (code !== 0) {
      return;
    }
    uni.showToast({
      title: '领取成功',
    });
    setTimeout(() => {
      getCoupon();
    }, 1000);
  }

  //  TODO 芋艿：待测试
  const shareInfo = computed(() => {
    if (isEmpty(state.goodsInfo)) return {};
    return sheep.$platform.share.getShareInfo(
      {
        title: state.goodsInfo.name,
        image: sheep.$url.cdn(state.goodsInfo.picUrl),
        desc: state.goodsInfo.introduction,
        params: {
          page: '2',
          query: state.goodsInfo.id,
        },
      },
      {
        type: 'goods', // 商品海报
        title: state.goodsInfo.name, // 商品名称
        image: sheep.$url.cdn(state.goodsInfo.picUrl), // 商品主图
        price: state.goodsInfo.price, // 商品价格
        original_price: state.goodsInfo.marketPrice, // 商品原价
      },
    );
  });
  const recommendReason = computed(() => {
    if (isEmpty(state.goodsInfo)) return [];
    return state.goodsInfo.recommendReason ? state.goodsInfo.recommendReason.split('\n') : [];
  });

  // async function getCoupon() {
  //   const { code, data } = await CouponApi.getCouponTemplateList(state.goodsId, 2, 10);
  //   if (code === 0) {
  //     state.couponInfo = data;
  //   }
  // }

  const noticeList = reactive([
    '汪**   在两分钟前兑换该品',
    '汪**   在两分钟前兑换该品',
    '汪**   在两分钟前兑换该品',
    '汪**   在两分钟前兑换该品',
  ]);
  // 倒计时
  const timeData = ref({});

  // 定义 onChange 方法
  const onChange = (e) => {
    timeData.value = e;
  };
  onLoad((options) => {
    // 非法参数
    if (!options.id) {
      state.goodsInfo = null;
      return;
    }
    state.goodsId = options.id;
    // 1. 加载商品信息
    SpuApi.getSpuDetail(state.goodsId).then((res) => {
      // 未找到商品
      if (res.code !== 0 || !res.data) {
        state.goodsInfo = null;
        return;
      }
      // 加载到商品
      state.skeletonLoading = false;
      //  处理商品加个问题
      res.data.marketPrice = fen2yuan(res.data.marketPrice);
      res.data.pointsPrice = fen2yuan(res.data.pointsPrice);
      res.data.price = fen2yuan(res.data.price);
      res.data.vipPrice = fen2yuan(res.data.vipPrice);
      state.goodsInfo = res.data;

      // 加载是否收藏
      if (isLogin.value) {
        FavoriteApi.isFavoriteExists(state.goodsId, 'goods').then((res) => {
          if (res.code !== 0) {
            return;
          }
          state.goodsInfo.favorite = res.data;
        });
      }


      console.log("规格， ", state.goodsInfo.skus[0]);
      // 默认选中第一个规格
      if (state.goodsInfo.skus && state.goodsInfo.skus.length > 0) {
        state.selectedSku = state.goodsInfo.skus[0];
      }
    });

    // 2. 加载优惠劵信息
    // getCoupon();

    // 3. 加载营销活动信息
    // ActivityApi.getActivityListBySpuId(state.goodsId).then((res) => {
    //   if (res.code !== 0) {
    //     return;
    //   }
    //   res.data.forEach(activity => {
    //     if ([1, 2, 3].includes(activity.type)) { // 情况一：拼团/秒杀/砍价
    //       state.activityList.push(activity);
    //     } else if (activity.type === 5) { // 情况二：满减送
    //       state.activityInfo.push(activity);
    //     } else { // 情况三：限时折扣 TODO 芋艿
    //       console.log('待实现！优先级不高');
    //     }
    //   });
    // });
  });

  onReachBottom(() => {
    console.log('到底了');
    uni.$emit('onReachBottom');
  });

</script>

<style lang="scss" scoped>
  .container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .custom-notice-bar {
    display: flex;
    flex-direction: column;
    height: 100px; /* 设置一个固定高度，以便内容可以滚动 */
    overflow: hidden;
  }

  .custom-notice-bar .uni-notice-bar__content-wrapper {
    display: flex;
    flex-direction: column;
  }

  .custom-notice-bar .uni-notice-bar__content-item {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 50px; /* 每行的高度 */
  }

  .detail-card {
    background-color: #ffff;
    margin: 14rpx 20rpx;
    border-radius: 10rpx;
    overflow: hidden;
  }

  @keyframes color-change {
    50% {
      background-color: #d72c0c;
    }
  }

  :deep(.ui-tabbar) {
    height: 130rpx;
  }

  .forward-color {
    animation: color-change 0.5s infinite;
    background-color: #ffb40e;
    color: #fff;
    height: 100%;
    width: 300rpx;
  }

  // 价格标题卡片
  .title-card {
    .price-box {
      .price-text {
        font-size: 42rpx;
        font-weight: 500;
        color: #ff3000;
        line-height: 30rpx;
        font-family: OPPOSANS;

        &::before {
          content: '￥';
          font-size: 30rpx;
        }
      }

      .origin-price-text {
        font-size: 26rpx;
        font-weight: 400;
        text-decoration: line-through;
        color: $gray-c;
        font-family: OPPOSANS;

        &::before {
          content: '￥';
        }
      }
    }

    .sales-text {
      font-size: 26rpx;
      font-weight: 500;
      color: $gray-c;
    }

    .discounts-box {
      .tag-content {
        flex: 1;
        min-width: 0;
        white-space: nowrap;
      }

      .tag-box {
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .tag {
        flex-shrink: 0;
        padding: 4rpx 10rpx;
        font-size: 24rpx;
        font-weight: 500;
        border-radius: 4rpx;
        color: var(--ui-BG-Main);
        background: var(--ui-BG-Main-tag);
      }

      .discounts-title {
        font-size: 24rpx;
        font-weight: 500;
        color: var(--ui-BG-Main);
        line-height: normal;
      }

      .cicon-forward {
        color: var(--ui-BG-Main);
        font-size: 24rpx;
        line-height: normal;
        margin-top: 4rpx;
      }
    }

    .title-text {
      font-size: 30rpx;
      font-weight: bold;
      line-height: 42rpx;
    }

    .subtitle-text {
      font-size: 26rpx;
      font-weight: 400;
      color: $dark-9;
      line-height: 42rpx;
    }
  }

  // 购买
  .buy-box {
    .add-btn {
      width: 214rpx;
      height: 72rpx;
      font-weight: 500;
      font-size: 28rpx;
      border-radius: 40rpx 0 0 40rpx;
      background-color: var(--ui-BG-Main-light);
      color: var(--ui-BG-Main);
    }

    .buy-btn {
      width: 214rpx;
      height: 72rpx;
      font-weight: 500;
      font-size: 28rpx;

      background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
      color: $white;
    }

    .disabled-btn {
      width: 428rpx;
      height: 72rpx;
      border-radius: 40rpx;
      background: #999999;
      color: $white;
    }
  }

  .model-box {
    height: 60vh;

    .model-content {
      height: 56vh;
    }

    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333333;
    }

    .subtitle {
      font-size: 26rpx;
      font-weight: 500;
      color: #333333;
    }
  }

  //放心购
  .middle-box {
    padding: 0 20rpx;

    .gridMenu {
      margin: 10rpx 0;

      .grid-text {
        margin: 10rpx 0;
      }
    }

    .hotBox {
      margin-bottom: 10px;
      border: 1px solid #eee;
      border-radius: 20rpx;
      padding: 20rpx;

      &-top {
        align-items: center;

        .first {
          margin-right: 10rpx;
        }

        .jifenIcon {
          background: linear-gradient(90deg, #fb7845, #ffbb5b);
          color: #fff;
          padding: 0 5rpx;
          border-radius: 25rpx;
        }
      }

      &-bot {
        color: #7b7b7b;
        margin: 15rpx 0;
      }

      .imageBox {
        display: flex;
        align-items: center;
        justify-content: space-around;
      }
    }
  }
</style>
